package city.spring.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.config.core.GrantedAuthorityDefaults;

/**
 * 角色代码处理工具
 *
 * @author HouKunLin
 * @date 2019/12/23 0023 12:07
 */
public class RoleUtils implements ApplicationContextAware, InitializingBean {
    private static String defaultRolePrefix = "ROLE_";
    private static ApplicationContext applicationContext;

    /**
     * @see RoleUtils#getAuthorityWithDefaultPrefix(java.lang.String, java.lang.String)
     */
    public static String getAuthorityWithDefaultPrefix(String role) {
        return getAuthorityWithDefaultPrefix(defaultRolePrefix, role);
    }

    /**
     * 获取默认前缀的权限。构建角色代码，自动添加 ROLE_ 前缀
     *
     * @param defaultRolePrefix 默认角色前缀
     * @param role              角色名称
     * @return 完整的角色名称
     * @see SecurityExpressionRoot#getRoleWithDefaultPrefix(java.lang.String, java.lang.String) 参考实现
     */
    public static String getAuthorityWithDefaultPrefix(String defaultRolePrefix, String role) {
        if (role == null) {
            return null;
        } else if (defaultRolePrefix != null && defaultRolePrefix.length() != 0) {
            return role.startsWith(defaultRolePrefix) ? role : defaultRolePrefix + role;
        } else {
            return role;
        }
    }

    /**
     * @see RoleUtils#getAuthorityRemoveDefaultPrefix(java.lang.String, java.lang.String)
     */
    public static String getAuthorityRemoveDefaultPrefix(String role) {
        return getAuthorityRemoveDefaultPrefix(defaultRolePrefix, role);
    }

    /**
     * 删除默认前缀的权限。构建权限代码，自动删除 ROLE_ 前缀
     *
     * @param defaultRolePrefix 默认角色前缀
     * @param role              角色名称
     * @return 删除默认前缀的权限
     */
    public static String getAuthorityRemoveDefaultPrefix(String defaultRolePrefix, String role) {
        if (role == null) {
            return null;
        } else if (defaultRolePrefix != null && defaultRolePrefix.length() != 0) {
            return role.startsWith(defaultRolePrefix) ? role.substring(defaultRolePrefix.length()) : role;
        } else {
            return role;
        }
    }

    public static String getDefaultRolePrefix() {
        return defaultRolePrefix;
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        RoleUtils.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        GrantedAuthorityDefaults bean = applicationContext.getBean(GrantedAuthorityDefaults.class);
        RoleUtils.defaultRolePrefix = bean.getRolePrefix();
    }
}
